package codeTop;

import java.util.HashSet;
import java.util.Set;

public class q160 {
    //遍历+hash表，很不优雅
    public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
        Set<ListNode> set = new HashSet<>();
        ListNode pa = headA;
        ListNode pb = headB;
        while (pa != null && pb != null) {
            boolean add = set.add(pa);
            if (!add) {
                return pa;
            }
            pa = pa.next;
            boolean add1 = set.add(pb);
            if (!add1) {
                return pb;
            }
            pb = pb.next;
        }
        while (pa != null) {
            boolean add = set.add(pa);
            if (!add) {
                return pa;
            }
            pa = pa.next;
        }
        while (pb != null) {
            boolean add1 = set.add(pb);
            if (!add1) {
                return pb;
            }
            pb = pb.next;
        }
        return null;
    }
    //双指针循环遍历，优雅！！！
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode pA = headA;
        ListNode pB = headB;
        while (pA != pB) {
            if (pA != null) {
                pA = pA.next;
            }else {
                pA = headB;
            }
            if (pB != null) {
                pB = pB.next;
            }else {
                pB = headA;
            }
        }
        return pA;
    }
}
